const fs = require('fs')
const path = require('path')

// 读取原始迁移脚本
const migratePath = path.join(__dirname, 'migrate-mock-to-db.js')
let content = fs.readFileSync(migratePath, 'utf8')

console.log('🔧 修复迁移脚本中的字段名...')

// 1. 修复authors表的字段名
// 将 user_id, pen_name, bio 替换为 name, description
content = content.replace(
  /INSERT INTO authors \(id, user_id, pen_name, bio, created_at\)/g,
  'INSERT INTO authors (id, name, description)'
)

content = content.replace(
  /VALUES \(\?, \?, \?, \?, NOW\(\)\)/g,
  'VALUES (?, ?, ?)'
)

content = content.replace(
  /\[author\.id, author\.user_id, author\.pen_name, author\.bio\]/g,
  '[author.id, author.pen_name, author.bio]'
)

// 2. 修复novels表的字段名
// 根据实际数据库结构调整字段映射
const fieldsMapping = {
  cover: 'cover_url',
  wordCount: 'word_count',
  chapterCount: 'chapter_count',
  viewCount: 'view_count',
  favoriteCount: 'favorite_count',
  ratingCount: 'rating_count',
  isVip: 'is_vip',
  lastChapterTitle: 'last_chapter_title',
  lastChapterTime: 'last_chapter_time'
}

// 替换字段名
for (const [oldField, newField] of Object.entries(fieldsMapping)) {
  const regex = new RegExp(`novel\\.${oldField}`, 'g')
  content = content.replace(
    regex,
    `novel.${oldField.replace(/([A-Z])/g, '_$1').toLowerCase()}`
  )
}

// 3. 移除createdAt和updatedAt的手动设置（数据库会自动处理）
content = content.replace(/novel\.createdAt/g, 'new Date().toISOString()')
content = content.replace(/novel\.updatedAt/g, 'new Date().toISOString()')

// 写入修复后的脚本
const fixedPath = path.join(__dirname, 'migrate-mock-to-db-fixed.js')
fs.writeFileSync(fixedPath, content)

console.log('✅ 迁移脚本修复完成，已保存为: migrate-mock-to-db-fixed.js')
console.log('📋 主要修复内容:')
console.log('- ✅ 修复authors表字段名映射')
console.log('- ✅ 修复novels表字段名映射')
console.log('- ✅ 调整时间戳处理方式')
